Introduction
In this article, I am going to explain about "Remote Validation", using MVC 5. Remote Validation is mainly used to check if the user or Mail ID exists or not in a database. Also, you can use it for any type of validation using Remote Attribute.
Most of the Web Applications need to validate the user or mail ID in the database. For this, the developers need to write huge amount of code. Due to this, I am going to achieve this task in very simple steps. Remote Validation normally works as jQuery validation.
Before learning about "Remote Validation", if you are beginner in MVC, you should read these -
What is Remote Validation?
Remote Validation permits the developer to call the controller action, using client side script. This is valuable when you need to perform out a back end query without performing a full Server side Postback.
Implement of "Remote Validation" in MVC Application.
Remote Validation is only an AJAX call, which approves the client's information. This can undoubtedly be proficient without using ASP.NET MVC 5. The situation for our demo is very basic. We have to ensure that the EmpName of the new user is one of a kind. The execution beneath makes a basic structure, which contains the TextBox control with the Id EmpName and other TextBox control with Id EmpMail.
Follow some simple steps to use remote validation in MVC 5
Step 1 - Create a MVC Application. See the image, given below-
Step 2 - Create a model "Employee.cs" inside "Model" folder. Use the code, given below-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace RemoteValidation.Models {
- public class Employee {
- //To Check userName
- [Remote("IsEmpNameExist", "Validation", ErrorMessage = "Employee name already exist")]
- public string EmpName {
- get;
- set;
- }
- //check User name and mailId.
- [Remote("IsEmpNameandMailExist", "Validation", ErrorMessage = "EmialId is already exist", AdditionalFields = "EmpName")]
- public string EmpMail {
- get;
- set;
- }
- }
- //Set static value in model.
- public static class EmployeeStaticData {
- public static List < Employee > UserList {
- get {
- return new List < Employee > {
- new Employee {
- EmpName = "Bikesh", EmpMail = "[email protected]"
- },
- new Employee {
- EmpName = "Navdeep", EmpMail = "[email protected]"
- }
-
- };
- }
- }
-
- }
- }
Step 3 - Create a Controller "ValidationController.cs" to Implement the Validation. In this Controller, I am creating an action, which is used to check, if the user exists or not. Also, you can check any type of the Validation.
- using RemoteValidation.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace RemoteValidation.Controllers {
- public class ValidationController: Controller {
- //For check both at a time .mailid and empName.
- [HttpGet]
- public JsonResult IsEmpNameandMailExist(string Empname, string EmpMail) {
-
- bool isExist = EmployeeStaticData.UserList.Where(u => u.EmpName.ToLowerInvariant().Equals(Empname.ToLower()) && u.EmpMail.ToLowerInvariant().Equals(EmpMail.ToLower())).FirstOrDefault() != null;
- return Json(!isExist, JsonRequestBehavior.AllowGet);
- }
- //To check only EmpName
- [HttpGet]
- public JsonResult IsEmpNameExist(string Empname) {
-
- bool isExist = EmployeeStaticData.UserList.Where(u => u.EmpName.ToLowerInvariant().Equals(Empname.ToLower())) != null;
- return Json(!isExist, JsonRequestBehavior.AllowGet);
- }
- }
- }
Step 4 - Create Controller to execute your action. Here, you can create any type of action to perform your task. Use the code, given below-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using RemoteValidation.Models;
-
- namespace RemoteValidation.Controllers {
- public class EmployeeController: Controller {
- //my action
- [HttpGet]
- public ActionResult AddUser() {
- Employee model = new Employee();
- return View(model);
- }
-
- }
- }
Step 5 - Right click on Action name "AddUser" add view. In this View, I am binding model "Employee". Using Razor control, I am creating a login page, which is designed, using bootstrap, CSS, and jQuery. Use the code, given below-
- @model RemoteValidation.Models.Employee
-
- <
- div class = "panel panel-primary" >
- <
- div class = "panel-heading panel-head" > Add User < /div> <
- div class = "panel-body" >
- @using(Html.BeginForm()) { <
- div class = "form-horizontal" >
- <
- div class = "form-group" >
- @Html.LabelFor(model => model.EmpName, new {
- @class = "col-lg-2 control-label"
- }) <
- div class = "col-lg-9" >
- @Html.TextBoxFor(model => model.EmpName, new {
- @class = "form-control"
- })
- @Html.ValidationMessageFor(model => model.EmpName) <
- /div> </div >
- <
- div class = "form-group" >
- @Html.LabelFor(model => model.EmpMail, new {
- @class = "col-lg-2 control-label"
- }) <
- div class = "col-lg-9" >
- @Html.TextBoxFor(model => model.EmpMail, new {
- @class = "form-control"
- })
- @Html.ValidationMessageFor(model => model.EmpMail) <
- /div> <
- /div> <
- div class = "form-group" >
- <
- div class = "col-lg-9" > < /div> <div class="col-lg-3"> <
- button class = "btn btn-success"
- id = "btnSubmit"
- type = "submit" >
- Submit <
- /button> <
- /div> <
- /div> <
- /div>
-
- <
- /div> <
- /div>
- @section scripts
-
- {
- @Scripts.Render("~/bundles/jqueryval")
- }
Step 6 - Don't forget this step. Add these lines in "Web.config" file. Use this code inside "<appseting>".
- <appSettings>
- <add key="ClientValidationEnabled" value="true" />
- <add key="UnobtrusiveJavaScriptEnabled" value="true" />
- </appSettings>
Step 7 -This step is also important because without adding "jquery.validate" and "jquery.validate.unobtrusive" this library works in background, which needs to be added in "bundle.config" file. Use the code, given below-
- using System.Web;
- using System.Web.Optimization;
-
- namespace RemoteValidation {
- public class BundleConfig {
- // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
- public static void RegisterBundles(BundleCollection bundles) {
- bundles.Add(new StyleBundle("~/Content/css").Include(
- "~/Content/css/bootstrap.css",
- "~/Content/css/font-awesome.css",
- "~/Content/css/site.css"));
-
- bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
- "~/Scripts/jquery-{version}.js"));
-
- bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
- "~/Scripts/jquery.validate*"));
- }
- }
- }
Step 8 - Now, set your "route.config" default controller and an action according your Application and run. If you have configured all the settings and implemented the code properly and followed all steps, you can see output screen, as shown below-
According to this image, you can see that I am typing "Bikesh". It is showing an error message "Employee name already exists" because I have written the hard-coded "Bikesh" in the model.
There are two situations to check Validation.
- You can check only Employee Name.
- You can check both conditions, "Employee Name" and Email Id.
I hope, you understood all the things about "Remote validation". You can also download the project and run it on your system.